<template>
  <div class="result-container">
    <!-- 基本信息+图表组合卡片 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span class="title">测评概览</span>
        </div>
      </template>
      <el-row :gutter="20" class="info-grid">
        <!-- 左侧信息卡片 -->
        <el-col :span="12">
          <!-- 测评标题 -->
          <div class="info-tag primary">
            <el-icon class="tag-icon">
              <Document/>
            </el-icon>
            <div class="tag-content">
              <div class="tag-label">测评主题</div>
              <div class="tag-value">{{ paperTitle }}</div>
            </div>
          </div>

          <!-- 时间信息行 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="info-tag secondary">
                <el-icon class="tag-icon">
                  <Clock/>
                </el-icon>
                <div class="tag-content">
                  <div class="tag-label">提交时间</div>
                  <div class="tag-value">{{ formattedDate }}</div>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="info-tag accent">
                <el-icon class="tag-icon">
                  <Timer/>
                </el-icon>
                <div class="tag-content">
                  <div class="tag-label">答题耗时</div>
                  <div class="tag-value">{{ formatDuration(totalTime) }}</div>
                </div>
              </div>
            </el-col>
          </el-row>

          <!-- 测评状态 -->
          <div class="info-tag status" :class="statusClass">
            <el-icon class="tag-icon">
              <CircleCheck/>
            </el-icon>
            <div class="tag-content">
              <div class="tag-label">当前状态</div>
              <div class="tag-value">{{ statusText }}</div>
            </div>
          </div>
          <!-- 得分 -->
          <div class="info-tag status" :class="statusClass">
            <el-icon class="tag-icon">
              <CircleCheck/>
            </el-icon>
            <div class="tag-content">
              <div class="tag-label">得分</div>
              <div class="tag-value">{{ totalScore }}</div>
            </div>
          </div>
        </el-col>

        <!-- 右侧饼图卡片 -->
        <el-col :span="12">
          <el-card class="chart-card">
            <h4 class="chart-title">维度分布</h4>
            <div class="chart-container">
              <template v-if="factorData.length">
                <v-chart :option="pieOption" autoresize/>
              </template>
              <el-empty v-else description="数据加载中..." :image-size="80"/>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>

    <!-- 因子得分卡片 -->
    <el-card class="factor-card">
      <template #header>
        <div class="card-header">
          <span class="title">维度得分分析</span>
        </div>
      </template>
      <el-table :data="factorData" stripe style="width: 100%">
        <el-table-column prop="name" label="心理维度" width="180"/>
        <el-table-column prop="score" label="得分" width="120">
          <template #default="{row}">
            <el-rate v-model="row.score"
                     disabled :max="100"
                     :colors="scoreColors"
                     show-score
            />
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="简要说明"/>
      </el-table>
    </el-card>

    <el-card class="analysis-card">
      <template #header>
        <div class="card-header">
          <span class="title">专业分析报告</span>
        </div>
      </template>

      <!-- 添加加载状态 -->
      <div v-if="!factorData.length" class="analysis-loading">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <p>正在生成专业分析...</p>
      </div>

      <!-- 分析内容容器 -->
      <div v-else class="analysis-content">
        <!-- 情绪健康分析 -->
        <div class="analysis-section">
          <h3 class="section-title">{{ analysisResult.emotion.title }}</h3>
          <p class="section-content">{{ analysisResult.emotion.content }}</p>
          <el-tooltip effect="dark" placement="right">
            <template #content>
              <div style="max-width: 300px">{{ analysisResult.emotion.tip }}</div>
            </template>
            <el-icon class="tip-icon"><InfoFilled /></el-icon>
          </el-tooltip>
        </div>

        <!-- 人际关系分析 -->
        <div class="analysis-section">
          <h3 class="section-title">{{ analysisResult.relationship.title }}</h3>
          <p class="section-content">{{ analysisResult.relationship.content }}</p>
          <el-tooltip effect="dark" placement="right">
            <template #content>
              <div style="max-width: 300px">{{ analysisResult.relationship.tip }}</div>
            </template>
            <el-icon class="tip-icon"><InfoFilled /></el-icon>
          </el-tooltip>
        </div>

        <!-- 行为表现分析 -->
        <div class="analysis-section">
          <h3 class="section-title">{{ analysisResult.behavior.title }}</h3>
          <p class="section-content">{{ analysisResult.behavior.content }}</p>
          <el-tooltip effect="dark" placement="right">
            <template #content>
              <div style="max-width: 300px">{{ analysisResult.behavior.tip }}</div>
            </template>
            <el-icon class="tip-icon"><InfoFilled /></el-icon>
          </el-tooltip>
        </div>

        <!-- 躯体症状分析 -->
        <div class="analysis-section">
          <h3 class="section-title">{{ analysisResult.somatic.title }}</h3>
          <p class="section-content">{{ analysisResult.somatic.content }}</p>
          <el-tooltip effect="dark" placement="right">
            <template #content>
              <div style="max-width: 300px">{{ analysisResult.somatic.tip }}</div>
            </template>
            <el-icon class="tip-icon"><InfoFilled /></el-icon>
          </el-tooltip>
        </div>
      </div>
    </el-card>

    <!-- 操作按钮组 -->
    <div class="action-btns">
      <el-button type="info" @click="handleBack">返回列表</el-button>
      <el-button type="success" @click="handleRetestAssessment(paperId)">重新测评</el-button>
      <el-button type="primary" @click="handleAIAnalysis">
        <el-icon>
          <MagicStick/>
        </el-icon>
        AI深度解读
      </el-button>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, getCurrentInstance} from 'vue'
import {Document, Clock, Timer, CircleCheck, MagicStick, InfoFilled, Loading} from '@element-plus/icons-vue'
import {use} from 'echarts/core'
import {CanvasRenderer} from 'echarts/renderers'
import {PieChart} from 'echarts/charts'
import {LegendComponent, TitleComponent, TooltipComponent} from 'echarts/components'
import VChart from 'vue-echarts'
import {retestAssessment} from "@/api/record/record.js"
import {generalScore} from "@/api/answer/answer.js"

// 初始化ECharts
use([CanvasRenderer, PieChart, TitleComponent, TooltipComponent, LegendComponent])

const {proxy} = getCurrentInstance()

// 响应式数据
const paperId = ref(proxy.$route.query.paperId)
const delFlag = ref(proxy.$route.query.delFlag)
const recordId = ref(proxy.$route.query.recordId)
const paperTitle = ref('')
const submitTime = ref(null)
const totalTime = ref(0)
const totalScore = ref(0)
const status = ref('')
const formattedDate = ref('')
const factorData = ref([])
const scoreColors = ref(['#99A9BF', '#F7BA2A', '#FF9900'])

const props = defineProps({
  scores: {
    type: Array,
    required: true,
    default: () => [],  // 添加默认值
    validator: value => {
      // 增强校验逻辑
      if (!Array.isArray(value)) {
        console.error('scores prop 必须是数组')
        return false
      }
      return value.length === 12 || value.length === 0 // 允许空数组
    }
  }
})

const dimensionCategories = {
  emotion: ['抑郁', '焦虑'],
  relationship: ['人际关系敏感', '敌对', '偏执'],
  behavior: ['强迫症状', '精神病性'],
  somatic: ['躯体化', '恐怖', '其他']
}

const analysisConfig = {
  emotion: {
    thresholds: [40, 60],
    suggestions: [
      {
        content: '情绪状态健康，继续保持良好的情绪调节习惯。',
        tip: '建议每周进行2-3次正念冥想练习'
      },
      {
        content: '存在轻度情绪困扰，建议关注情绪波动规律。',
        tip: '推荐使用情绪日记记录每日心情变化'
      },
      {
        content: '情绪状态需要专业关注，建议寻求心理咨询。',
        tip: '可联系我们的专业心理咨询师进行深入评估'
      }
    ]
  },
  relationship: {
    thresholds: [35, 50],
    suggestions: [
      {
        content: '社交能力良好，人际关系和谐。',
        tip: '保持定期社交活动有助于维持良好状态'
      },
      {
        content: '存在轻度社交回避倾向，建议加强社交互动。',
        tip: '尝试每周参加1次社交活动逐步改善'
      },
      {
        content: '人际关系压力显著，建议进行社交技能训练。',
        tip: '推荐参加我们的人际关系工作坊'
      }
    ]
  },
  behavior: {
    thresholds: [30, 45],
    suggestions: [
      {
        content: '行为表现正常，自我调节能力良好。',
        tip: '保持规律的作息时间有助于维持现状'
      },
      {
        content: '存在轻度行为异常，建议关注日常行为模式。',
        tip: '可尝试使用行为记录表进行自我观察'
      },
      {
        content: '需要专业行为干预，建议进行认知行为评估。',
        tip: '我们的CBT疗法可有效改善当前状况'
      }
    ]
  },
  somatic: {
    thresholds: [25, 40],
    suggestions: [
      {
        content: '无明显躯体化症状，生理状态良好。',
        tip: '保持适度运动有助于维持身体健康'
      },
      {
        content: '存在轻度躯体反应，建议关注心身联系。',
        tip: '尝试进行放松训练缓解身体紧张'
      },
      {
        content: '躯体症状明显，建议进行医学评估。',
        tip: '推荐先进行体检排除生理疾病因素'
      }
    ]
  }
}

const categoryAverages = computed(() => {
  if (!factorData.value || !factorData.value.length) return {}

  return Object.entries(dimensionCategories).reduce((acc, [category, names]) => {
    try {
      const matchedScores = factorData.value
          .filter(item => names.includes(item.name))
          .map(item => item.score)

      acc[category] = matchedScores.length > 0
          ? matchedScores.reduce((sum, score) => sum + score, 0) / matchedScores.length
          : 0
    } catch (e) {
      console.error('计算分类平均值出错:', e)
      acc[category] = 0
    }
    return acc
  }, {})
})

const analysisResult = computed(() => {
  console.log('当前分类平均分:', JSON.parse(JSON.stringify(categoryAverages.value)))
  // 处理空数据情况
  if (Object.keys(categoryAverages.value).length === 0) {
    return {
      emotion: null,
      relationship: null,
      behavior: null,
      somatic: null
    }
  }

  return Object.entries(analysisConfig).reduce((acc, [category, config]) => {
    try {
      const avgScore = categoryAverages.value[category] || 0
      let level = 0

      if (avgScore >= config.thresholds[1]) level = 2
      else if (avgScore >= config.thresholds[0]) level = 1

      acc[category] = {
        title: getCategoryTitle(category),
        content: config.suggestions[level]?.content || '暂无分析结果',
        tip: config.suggestions[level]?.tip || '请咨询专业医生',
        score: avgScore.toFixed(1)
      }
    } catch (e) {
      console.error('生成分析结果出错:', e)
      acc[category] = {
        title: getCategoryTitle(category),
        content: '分析数据异常',
        tip: '请联系技术支持',
        score: 'N/A'
      }
    }
    return acc
  }, {})
})

// 获取分类标题
const getCategoryTitle = (category) => {
  const titles = {
    emotion: '情绪健康分析',
    relationship: '人际关系评估',
    behavior: '行为表现分析',
    somatic: '躯体症状评估'
  }
  return titles[category] || '综合评估'
}

// 计算属性
const statusText = computed(() => status.value === '1' ? '已完成' : '未完成')
const statusClass = computed(() => status.value === '1' ? 'success' : 'warning')

const pieOption = computed(() => ({
  title: {
    text: '维度分布',
    left: 'center',
    textStyle: {
      fontSize: 14,
      color: '#606266'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: ({name, percent, value}) =>
        `${name}<br>得分：${value}<br>占比：${percent}%`
  },
  legend: {
    orient: 'vertical',
    right: '5%',
    top: 'middle',
    align: 'left',
    itemGap: 12,
    itemWidth: 10,
    itemHeight: 12,
    padding: [0, 20],
    formatter: name => {
      const item = factorData.value.find(v => v.name === name)
      return item ? `${name} (${item.score}分)` : name
    }
  },
  series: [{
    type: 'pie',
    center: ['35%', '55%'],
    radius: ['35%', '65%'],
    data: factorData.value.length
        ? factorData.value.map(item => ({name: item.name, value: item.score}))
        : [{name: '暂无数据', value: 0}],
    label: {
      show: true,
      formatter: '{b}: {d}%'
    }
  }]
}))

// 返回方法
const handleBack = () => {
  proxy.$router.push({path: '/history'})
}

// 重新测评
const handleRetestAssessment = (paperId) => {
  retestAssessment(paperId).then(response => {
    if (response) {
      proxy.$router.push({
        path: '/examPage',
        query: {paperId}
      })
    }
  })
}

// ai解析
const handleAIAnalysis = () => {
  proxy.$router.push({
    path: '/askAi',
    query: {
      paperId: paperId.value,
      recordId: recordId.value,
      delFlag: delFlag.value,
    }
  })
}

const formatterDate = () => {
  formattedDate.value = new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).format(new Date(submitTime.value)).replace(/\//g, '-')
}

const formatDuration = (milliseconds) => {
  if (!milliseconds || isNaN(milliseconds)) return '0 分钟'
  return `${(milliseconds / 60000).toFixed(1)} 分钟`
}

const getScore = () => {
  generalScore(paperId.value, delFlag.value, recordId.value).then(response => {
    if (response.data.recordId) {
      recordId.value = response.data.recordId
    }
    totalScore.value = response.data.totalScore
    paperTitle.value = response.data.paperTitle
    submitTime.value = response.data.submitTime
    totalTime.value = response.data.totalTime
    status.value = response.data.status
    factorData.value = response.data.symptomClusterDTOList
    console.log("响应结果：",response)
    formatterDate()
  })
}

onMounted(() => {
  getScore()
})
</script>

<style scoped>
.analysis-card {
  margin: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.analysis-section {
  position: relative;
  padding: 18px;
  margin: 16px 0;
  background: #f8f9fc;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.analysis-section:hover {
  transform: translateX(5px);
  box-shadow: 2px 2px 8px rgba(0,0,0,0.08);
}

.section-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  color: #409eff;
}

.section-content {
  margin: 0;
  line-height: 1.6;
  color: #606266;
}

.tip-icon {
  position: absolute;
  right: 12px;
  top: 12px;
  color: #909399;
  cursor: pointer;
  transition: color 0.2s;
}

.tip-icon:hover {
  color: #409eff;
}

.result-container {
  background: linear-gradient(135deg, #f8fbff 0%, #f5f9fc 100%);
  min-height: 100vh;
  padding: 30px 50px;
}

.el-card {
  margin-bottom: 25px;
  border-radius: 15px;
  border: none;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05);

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 12px 25px rgba(0, 0, 0, 0.12);
  }
}

.card-header {
  padding: 18px 25px;

  .title {
    font-size: 20px;
    color: #2c3e50;
    font-weight: 600;
    letter-spacing: 0.5px;
  }
}

.info-grid {
  --primary-color: #36a2eb;
  --secondary-color: #4ecb73;
  --accent-color: #ff9f43;
  --success-color: #67c23a;
  --warning-color: #e6a23c;
}

.info-tag {
  padding: 25px;
  margin-bottom: 20px;
  border-radius: 15px;
  display: flex;
  align-items: center;
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0.1;
  }

  .tag-icon {
    font-size: 32px;
    margin-right: 20px;
    flex-shrink: 0;
  }

  .tag-label {
    font-size: 13px;
    letter-spacing: 1px;
    margin-bottom: 8px;
    opacity: 0.8;
  }

  .tag-value {
    font-size: 18px;
    font-weight: 600;
    line-height: 1.3;
  }

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);

    &::before {
      opacity: 0.15;
    }
  }
}

.primary {
  background: linear-gradient(145deg, rgba(54, 162, 235, 0.15) 0%, rgba(54, 162, 235, 0.05) 100%);

  &::before {
    background: var(--primary-color);
  }

  .tag-icon, .tag-label {
    color: var(--primary-color);
  }
}

.secondary {
  background: linear-gradient(145deg, rgba(78, 203, 115, 0.15) 0%, rgba(78, 203, 115, 0.05) 100%);

  &::before {
    background: var(--secondary-color);
  }

  .tag-icon, .tag-label {
    color: var(--secondary-color);
  }
}

.accent {
  background: linear-gradient(145deg, rgba(255, 159, 67, 0.15) 0%, rgba(255, 159, 67, 0.05) 100%);

  &::before {
    background: var(--accent-color);
  }

  .tag-icon, .tag-label {
    color: var(--accent-color);
  }
}

.status.success {
  background: linear-gradient(145deg, rgba(103, 194, 58, 0.15) 0%, rgba(103, 194, 58, 0.05) 100%);

  &::before {
    background: var(--success-color);
  }

  .tag-icon, .tag-label {
    color: var(--success-color);
  }
}

.status.warning {
  background: linear-gradient(145deg, rgba(230, 162, 60, 0.15) 0%, rgba(230, 162, 60, 0.05) 100%);

  &::before {
    background: var(--warning-color);
  }

  .tag-icon, .tag-label {
    color: var(--warning-color);
  }
}

.chart-card {
  height: 100%;
  background: #fff;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 25px rgba(0, 0, 0, 0.12);
  }

  .chart-title {
    font-size: 16px;
    color: #34495e;
    margin: 0 0 15px 10px;
  }

  .chart-container {
    height: 450px;
    padding: 15px;
  }
}

.analysis-card {
  .el-card__body {
    display: grid;
    gap: 25px;
    grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
    padding: 25px;
  }

  .analysis-section {
    padding: 25px;
    background: linear-gradient(145deg, #ffffff 0%, #f8fafc 100%);
    border-radius: 12px;
    transition: all 0.3s ease;
    cursor: pointer;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 6px 15px rgba(0, 0, 0, 0.08);

      .section-title {
        color: #36a2eb;
      }
    }

    .section-title {
      font-size: 17px;
      color: #2c3e50;
      margin-bottom: 12px;
      transition: color 0.3s ease;
    }

    .section-content {
      font-size: 14px;
      color: #7f8c8d;
      line-height: 1.7;
    }
  }
}

.action-btns {
  margin: 40px 0;
  padding: 25px 0;
  display: flex;
  gap: 25px;

  .el-button {
    padding: 12px 28px;
    border-radius: 10px;
    font-size: 14px;
    letter-spacing: 0.5px;
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.12);
    }

    .el-icon {
      margin-right: 8px;
      font-size: 16px;
    }
  }
}

.el-table {
  border-radius: 12px;
  overflow: hidden;

  :deep(th) {
    background: #f8f9fa !important;
    font-weight: 600;
  }

  :deep(.cell) {
    padding: 12px 15px;
  }

  :deep(.el-rate) {
    display: flex;
    align-items: center;
  }
}
</style>
